package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.config.SMSUtils;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 移动端用户管理
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        String code = RandomStringUtils.random(4, false, true);
        session.setAttribute("code",code);
        //SMSUtils.sendMessage(phone,code);
        log.info("code为{}",code);
        return R.success("短信发送成功");

    }
    @PostMapping("login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session){
        String phone = map.get("phone");
        String code = map.get("code");
        String code1 =(String) session.getAttribute("code");
        if (!StringUtils.equals(code,code1)){
            return R.error("验证码错误");
        }
        User user = userService.lambdaQuery().eq(User::getPhone, phone).one();
        if (user==null){
            user=new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        session.setAttribute("user",user.getId());
        return R.success(user);
    }


}
